package fr.mairie.parc.page.user;

import javax.annotation.Resource;

import org.apache.click.control.Form;
import org.apache.click.control.ImageSubmit;
import org.apache.click.util.Bindable;
import org.springframework.context.ApplicationContext;

import fr.mairie.parc.context.AppContext;
import fr.mairie.parc.control.user.UserFields;
import fr.mairie.parc.domain.User;
import fr.mairie.parc.page.BorderPage;
import fr.mairie.parc.service.UserManager;

public class UserPage extends BorderPage{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;


	@Resource private UserManager userManager;

	@Bindable protected Form form = new Form();

	protected UserFields fields = new UserFields();

	public UserPage() {
		fields.addAll(form);
		form.add(new ImageSubmit("OK", "/assets/images/32x32/accept.png", this,"onSubmit"));
		form.add(new ImageSubmit("Cancel", "/assets/images/32x32/cancel.png",this, "onCancelClick"));

	}

	@Override
	public void onInit() {
		super.onInit();
		ApplicationContext ctx = AppContext.getApplicationContext();
		userManager = (UserManager) ctx.getBean("userManager");

	}

	public boolean onSubmit() {
		String msg;
		if (form.isValid()) {
			User user = new User();

			form.copyTo(user);
			userManager.addUser(user);


			form.clearValues();

			msg = "A new user  record has been created.";
			addModel("msg", msg);

		} else {
			msg = getMessage("msg-form-error", form.getError());
		}

		return true;
	}
	public boolean onCancelClicked() {
        setRedirect(ListUserPage.class);
        return false;
    }

}
